package com.quanquan.management.config.shiro;

import com.quanquan.management.entity.SysPermission;
import com.quanquan.management.entity.SysRole;
import com.quanquan.management.entity.SysUser;
import com.quanquan.management.repository.SysPermissionRepository;
import com.quanquan.management.repository.SysRoleRepository;
import com.quanquan.management.repository.SysUserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author:lihonglinag
 * @date:2019-03-21 16:23
 * @version:v 1.0.0
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user= (SysUser) super.getAvailablePrincipal(principals);
        if(user==null){
            throw new AuthenticationException("用户不存在");
        }
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        List<SysRole> roleLst = sysRoleRepository.getRoleByUserId(user.getId());
        for (SysRole role : roleLst) {
            simpleAuthorInfo.addRole(role.getId());
        }
        List<SysPermission> permissions = sysPermissionRepository.getPermissionByUserId(user.getId());
        Set<String> permissionsStringSet=new HashSet<>();
        for (SysPermission permission : permissions) {
            permissionsStringSet.add(permission.getUrl());
        }
        simpleAuthorInfo.setStringPermissions(permissionsStringSet);
        return simpleAuthorInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username = token.getUsername();

        SysUser user = sysUserRepository.findByUsername(username);
        if (user == null) {
            throw new AuthenticationException("用户不存在");
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
